<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="showDialog" @close="cancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      label-width="120px"
      :model="formData"
      :rules="rules"
      ref="deptForm"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          style="width: 80%"
          placeholder="1-50个字符"
          v-model="formData.name"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          style="width: 80%"
          placeholder="1-50个字符"
          v-model="formData.code"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          style="width: 80%"
          placeholder="请选择"
          v-model="formData.manager"
          @focus="getEmployeesSimple"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
          v-model="formData.introduce"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartmentDetail,
  updateDepartments,
} from "@/api/departments";
import { getEmployeesSimple } from "@/api/employees";

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    //当前操作的节点
    treeNode: {
      type: Object,
      default: null,
    },
  },
  data() {
    //检查部门名称是否重复
    const checkNameRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments();
      let isRepeat = false;
      if (this.formData.id) {
        //编辑模式 在数据库有数据 并且名字不能与同级部门名字重复
        isRepeat = depts
          .filter(
            (item) =>
              item.pid === this.treeNode.id && item.id !== this.formData.id
          )
          .some((item) => item.name === value);
      } else {
        // 新增模式
        isRepeat = depts
          .filter((item) => item.id === this.treeNode.id)
          .some((item) => itme.name === value);
      }

      //如果isrepeat是true说明找到了相同的部门名称
      isRepeat
        ? callback(new Error(`同级名称下已经存在${value}部门`))
        : callback();
    };

    //检查部门编码是否重复
    const checkCodeRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments();
      let isRepeat = false;
      if (this.formData.id) {
        //编辑模式
        isRepeat = depts.some(
          (item) => item.id !== this.formData.id && item.code === value && value
        );
      } else {
        //这里判断，要求编码和所有部门编码都不能重复，由于历史数据可能 没有code 所以说这里加一个强制性条件就是value值不为空才可以判断
        isRepeat = depts.some((item) => item.code === value && value); //value=value != ""
      }

      isRepeat ? callback(new Error(`${value}编码已存在`)) : callback();
    };
    return {
      formData: {
        name: "", //部门名称
        code: "", //部门编码
        manager: "", //部门管理者
        introduce: "", //部门介绍
      },
      peoples: [],
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            mix: 1,
            max: 50,
            message: "部门名称长度为1-50字符",
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: checkNameRepeat,
          },
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            mix: 1,
            max: 50,
            message: "部门编码长度为1-50字符",
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: checkCodeRepeat,
          },
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            mix: 1,
            max: 300,
            message: "部门介绍长度为1-300字符",
            trigger: "blur",
          },
        ],
      }, //效验规则 {key:数组}
    };
  },
  computed: {
    showTitle() {
      return this.formData.id ? "编辑部门" : "新增部门";
    },
  },
  methods: {
    btnOK() {
      //手动效验表单
      this.$refs.deptForm.validate(async (isOk) => {
        if (isOk) {
          // 判断是新增还是编辑
          if (this.formData.id) {
            // 编辑
            await updateDepartments(this.formData);
          } else {
            //新增
            //表示可以提交表单
            await addDepartments({
              ...this.formData,
              pid: this.treeNode.id,
            });
          }

          // 告诉父组件更新数据
          this.$emit("addDepts");
          this.$emit("update:showDialog", false);
          //关闭dialog的时候会触发el-dialog的close事件，所以数据也能被清除
        }
      });
    },
    cancel() {
      //重置数据
      this.formData = {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      };
      this.$emit("update:showDialog", false);
      //重置表单里的数据 但是只能重置定义在data中的数据，对于后面添加的数据不会重置
      this.$refs.deptForm.resetFields();
    },
    //下拉选择列表获取员工简单列表信息
    async getEmployeesSimple() {
      this.peoples = await getEmployeesSimple();
    },

    //获取部门详情方法
    async getDepartmentDetail(id) {
      this.formData = await getDepartmentDetail(id);
    },
  },
};
</script>

<style scope>
</style>